import React, { useState, useEffect } from 'react';
import DComponent from './DComponent';
import { ReactSortable } from "ereact-sortablejs";
import { parse } from './parse';
import _ from 'lodash';


const DRoot = (props) => {

    //选项
    const opts = {
        group: {
            name: 'visualui',
            pull: true,
            put: true,
        },
        sort: true,
    };

    //样式
    const style = {
        width: '95%',
        //height: '95%',
        minHeight:'600px',
        borderWidth: '1px',
        borderStyle: 'solid',
        borderColor: '#1890ff',
        //margin:'2px'
        padding: '1px'
    }


    const { node, onSchemaChange } = props;
    const { children = [] } = node;

    // const [state, setState] = useState(node.children || []);



    // //node.children发生变化时
    // useEffect(() => {
    //     setState(node.children);
    // }, [node.children]);


    //state发生变化时
    // useEffect(() => {
    //     node.children = state;
    //     onSchemaChange({ type: 'root' }, node);
    // }, [state]);



    return <ReactSortable
        style={style}
        {...opts}
        list={children}
        setList={(newList) => {

            const newSchema = parse(newList);
            node.children = newSchema;
            onSchemaChange({ sourceType: 'root' }, _.cloneDeep(node));

            //setState(newSchema);
        }}>

        {children.map((subNode, index) => {

            return <DComponent

                key={index}

                root={node}
                parent={node}
                node={subNode}
                pindex={index}
                onSchemaChange={onSchemaChange}

            />
        })}
    </ReactSortable>

}

export default DRoot;